package com.myph.phctrl_t;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.phctrl_t.R;
import com.myph.chart.IDemoChart;
import com.myph.chart.ShowChart;
import com.myph.model.ClientSocketNew;
import com.myph.model.Util;

public class MeasureActivity extends Activity implements OnClickListener {

	private long prevClickTime = 0;
	private String TAG = "DEBUG";
	Activity activity;
	Button btn_once_data, btn_instant, btn_send_to_web;
	EditText edt_times;
	TextView txt_ph_data;
	String ip, port;
	String on_or_off;
	StringBuilder response = new StringBuilder();
	int reqMode = 1;// 1:$phnow 2:$phhis
	int phhisNum = 1;

	double[] xArray = null;
	double[] yArray = null;
	String timeStr, gap_time;// 测一次认为gap_time=30s
	String startTime;
	String dataSetString;
	
	RequestQueue mQueue = null;
	StringRequest stringRequest = null;

	String hauser,hadevice;
	// double [] result_data_for_web = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_measure);

		activity = this;

		ip = Util.getSharedPref(this, "ip");
		port = Util.getSharedPref(this, "port");
		hauser = "9faaeac914223f7b233b95c6139528ec";
		hadevice = "55f312f84e7785aa1efa552acbf251db";
		
		txt_ph_data = (TextView) findViewById(R.id.txt_ph_data);
		btn_send_to_web = (Button) findViewById(R.id.btn_send_to_web);
		btn_once_data = (Button) findViewById(R.id.btn_once_data);
		btn_instant = (Button) findViewById(R.id.btn_instant);
		edt_times = (EditText) findViewById(R.id.txt_times);

		btn_once_data.setOnClickListener(this);
		btn_instant.setOnClickListener(this);
		btn_send_to_web.setOnClickListener(this);
		
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:// instant data
				
				ClientSocketNew csn = new ClientSocketNew(ip, port, handler);
				String res = "$phnow#";
				csn.setNewRequest(res, response);
				csn.start();
				reqMode = 1;
				break;
			case 2:// instant k data
				String res2 = "$phhis,";
				if (edt_times.getText() == null
						|| edt_times.getText().toString().equals("")) {
					Util.myToast(getApplicationContext(), "次数不能为空");
					return;
				}
				try {
					int num = Integer.parseInt(edt_times.getText().toString());
					phhisNum = num;
				} catch (Exception e) {
					Util.myToast(getApplicationContext(), "数据不合法");
					return;
				}

				res2 += edt_times.getText().toString() + "#";
				ClientSocketNew csn2 = new ClientSocketNew(ip, port, handler);
				csn2.setNewRequest(res2, response);
				csn2.start();
				reqMode = 2;
				break;

			case 5:
				// TODO:
				if (yArray == null) {
					Util.myToast(getApplicationContext(), "尚未发送过数据");
					return;
				}

				mQueue = Volley.newRequestQueue(activity);
				String httpurl = "http://phctrl.oschina.mopaas.com/chart/apiInsert.php?";
				httpurl += "hashuser=" + hauser
						+ "&";
				httpurl += "hashdevice=" + hadevice
						+ "&";

				// httpurl +=
				// "startTime=2015-08-28 22:57:44&frequence=80&dataSet=7.1,7.2,7.3";

				httpurl += "startTime=" + timeStr + "&";
				httpurl += "frequence=" + gap_time + "&";
				httpurl += "dataSet=";
				
				dataSetString = "";
				for (int i = 0; i < yArray.length; ++i) {
					dataSetString += String.valueOf(yArray[i]);
					if (i != yArray.length - 1) {
						dataSetString += ",";
					}
				}
				httpurl += dataSetString;
				// TODO:
				httpurl = httpurl.replaceAll(" ", "%20");
				Log.d(TAG, "url:" + httpurl);
			
				stringRequest = new StringRequest(Request.Method.GET, httpurl,
						new Response.Listener<String>() {
							@Override
							public void onResponse(String response) {
								Log.d(TAG, "response:" + response);
								if (response == null
										|| !response.contains("OK")) {
									Log.d(TAG, "fail");

									Util.myToast(activity, "数据发送失败");

								} else {
									Log.d(TAG, "OK");

									
									Util.myToast(activity, "数据发送成功");

								}
							}

						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								Log.e(TAG, error.getMessage(), error);

								Util.myToast(activity, "网络状况不好");

							}

						})

				;

				stringRequest.setRetryPolicy(new DefaultRetryPolicy(5 * 1000,
						1, 1.0f));
				mQueue.add(stringRequest);
				break;
			case 1002:

				Toast.makeText(getApplicationContext(), "fail to connect",
						Toast.LENGTH_SHORT).show();
				finish();
				break;
			case 1003:
				// $T:2015,08,15,20,00,00,PH:0800#
				// $T:2015,08,14,20,00,00,PH:0800#
				// $T:2015,08,13,20,00,00,PH:0800#
				if (response != null) {
					String resString = response.toString();
					int indexSt = response.indexOf("$");
					int indexEd = response.lastIndexOf("#");//最后一个#
					if (indexEd == -1 || indexSt == -1 || indexSt >= indexEd) {
						Util.myToast(getApplicationContext(), "数据解析失败");
						return;
					} else {
						if (reqMode == 1) {// $0780#
							resString = resString.substring(indexSt + 1,
									indexEd);
						} else if (reqMode == 2) {// $T:2015,08,15,20,00,00,PH:0800#
							resString = resString.substring(indexSt + 1);//第一个$要去掉,否则第一个split的结果为空""
						} else {
							Util.myToast(getApplicationContext(), "请求出错~");
							return;
						}
					}
					if (resString.equals("")) {
						Util.myToast(getApplicationContext(), "没有新数据~");
					} else {
						Log.d("response:", resString);
//						resString = resString.replaceAll("\n","");
						String[] str_totalYArray = resString.split("\\$");//多条数据
						
						String[] str_yArray = resString.split(",");//第1条数据
						
						xArray = null;
						yArray = null;
						timeStr = "";

//						int year,month,day,date,minute,second;
						String[] timeStrSet = null;
						if (reqMode == 1) {
							xArray = new double[str_yArray.length];
							yArray = new double[str_yArray.length];
							SimpleDateFormat df = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");// 设置发送时间
							timeStr = df.format(new Date());
							timeStrSet = new String[1];
							timeStrSet[0] = timeStr;
						} else if (reqMode == 2) {
							if (str_yArray.length < 6) {
								Util.myToast(getApplicationContext(), "接收数据出错~");
							}
							
							
							xArray = new double[str_totalYArray.length];
							yArray = new double[str_totalYArray.length];
							str_yArray[0] = str_yArray[0].substring(2);
							timeStr = str_yArray[0] + "-" + str_yArray[1] + "-"
									+ str_yArray[2] + " " + str_yArray[3] + ":"
									+ str_yArray[4] + ":" + str_yArray[5];
							
							timeStrSet = new String[yArray.length];
//							timeStrSet[0] = timeStr;
							// for (int j = 0; j < 6; ++j) {
							// timeStr += str_yArray[j];
							// }
							
						}

						if (reqMode == 1) {
							gap_time = "30";// 间隔最短为30s
						} else if (reqMode == 2) {
							// 发送间隔时间
							gap_time = Util.getSharedPref(
									getApplicationContext(), "gap_time");
							gap_time = String.valueOf(Integer.parseInt(gap_time)*30);
							if (gap_time == null) {
								gap_time = "30";// 最小时间间隔
							}
						}

						if (reqMode == 1) {// 只有一条数据
							xArray[0] = 0;
							yArray[0] = Double.parseDouble(str_yArray[0])/100.0;

						} else if (reqMode == 2) {// 倒计时间
							for (int i = 0; i < yArray.length; ++i) {
								//T:2015,08,13,20,00,00,PH:0800# 去掉了'$'
								//T:2015,08,13,20,00,00,PH:0800#
								
								String tmp = str_totalYArray[i];
								String tmpTimeStr = tmp.substring(tmp.indexOf("T:")+2,tmp.indexOf(",PH:"));
								String[] tmpTmpTimeStr = tmpTimeStr.split(",");
								String tmpTimeStrRes = tmpTmpTimeStr[0] + "-" + tmpTmpTimeStr[1] + "-"
								+ tmpTmpTimeStr[2] + " " + tmpTmpTimeStr[3] + ":"
								+ tmpTmpTimeStr[4] + ":" + tmpTmpTimeStr[5];
								timeStrSet[i] = tmpTimeStrRes;
								
								
								
								tmp = tmp.substring(tmp.indexOf("PH:")+3,tmp.indexOf("#"));
								
								xArray[i] = i;
								yArray[yArray.length-1-i] = Double
										.parseDouble(tmp)/100.0;
								Log.d("yArray","yArray["+i+"]"+yArray[yArray.length-1-i]);
							}
						}
						dataSetString = "时间";
						for(int jj=0;jj<14+14+3;++jj)//为了对齐
							dataSetString += " ";
						
						dataSetString += "pH数据\n";
						String tmpTimeString = timeStr;
					
						for (int i = 0; i < yArray.length; ++i) {
							dataSetString += timeStrSet[i]+"   ";
							
							dataSetString += String.valueOf(yArray[yArray.length-1-i]);
							if (i != yArray.length - 1) {
								dataSetString += "\n";
							}
						}
						
						txt_ph_data.setText(dataSetString);

						
						if(reqMode == 2){
							// TODO:显示折线图
							Util.myToast(getApplicationContext(), "显示折线图");
	
							// result_data_for_web = new double[yArray.length];
							// result_data_for_web = yArray.clone();
							//
							ShowChart sc = new ShowChart();
							sc.setTitle("phctrl " + timeStr + "," + gap_time);// 将这些信息都显示上去
							sc.setXArray(xArray);
							sc.setYArray(yArray);
							IDemoChart[] mCharts = new IDemoChart[] { sc };
							Intent intent = mCharts[0]
									.execute(getApplicationContext());
							startActivity(intent);
						}else{
							Util.myToast(getApplicationContext(),"测量结束");
						}
//						finish();
					}
				} else {
					Toast.makeText(getApplicationContext(), "异常",
							Toast.LENGTH_SHORT).show();
				}
				break;

			case 1004:
				Toast.makeText(getApplicationContext(), "连接超时,操作失败",
						Toast.LENGTH_SHORT).show();
				finish();
				break;
			case 2000://for test
				
				ShowChart sc = new ShowChart();
				sc.setTitle("phctrl " + "2015-8-31 10:31:00" + "," + 60);// 将这些信息都显示上去
				xArray = new double[10];
				yArray = new double[10];
				for(int i=0;i<10;++i){
					xArray[i] = i;
					yArray[i] = 9.6;
				}
				yArray[2] = 9.8;
				yArray[3] = 9.8;
				yArray[4] = 9.7;
				yArray[5] = 9.7;
				for(int i=6;i<9;++i){
					yArray[i] = 9.6;
				}
				yArray[9] = 9.7;
				
				sc.setXArray(xArray);
				sc.setYArray(yArray);
				IDemoChart[] mCharts = new IDemoChart[] { sc };
				Intent intent = mCharts[0]
						.execute(getApplicationContext());
				startActivity(intent);

				finish();
				break;
			default:
				Toast.makeText(getApplicationContext(), "handler error!",
						Toast.LENGTH_LONG).show();
				break;
			}

		}
	};

	public void sendMsg(int what, Handler handler) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	@Override
	public void onClick(View v) {
		long pressGap = System.currentTimeMillis() - prevClickTime;
		if(pressGap < 1000){
			return;
		}else{
			prevClickTime = System.currentTimeMillis();
		}
		
		switch (v.getId()) {
		case R.id.btn_once_data:
			sendMsg(1, handler);
//			sendMsg(2000, handler);
			break;
		case R.id.btn_instant:
			sendMsg(2, handler);
			break;
		case R.id.btn_send_to_web:
			sendMsg(5, handler);
			break;
		default:
			break;
		}
	}
}